package xiaolong.lian.util;


import org.mindrot.jbcrypt.BCrypt;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Auth {
    //token
    private static String salt = "je$1kd6@32k?kep(_ew84om";
    public static final int validDays = 7;
    //文档操作权限检查，操作者是否是创建者
    private static boolean permissionChecked = false;

    public static String generateToken(String tel){
        Calendar calendar = new GregorianCalendar();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        String generateTime = String.valueOf(calendar.getTime().getTime());
        return generateTime +"#"+ BCrypt.hashpw(tel+generateTime+salt, BCrypt.gensalt());
    }

    public static boolean isValidToken(String tel, String token){
        int index = token.indexOf('#');
        if(index < 1 || index == token.length()-1)
            return false;
        String generateTime = token.substring(0, index);
        token = token.substring(index+1);
        if(BCrypt.checkpw(tel+generateTime+salt, token)){
            Date now = new Date();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(new Date(Long.parseLong(generateTime)));
            calendar.add(Calendar.DATE, validDays);
            if(now.before(calendar.getTime())){
                return true;
            }
        }
        return false;
    }

    public static void setPermissionChecked(){
        permissionChecked = true;
    }

    public static boolean permissionChecked(){
        return permissionChecked;
    }

    public static void setPermissionUnchecked(){
        permissionChecked = false;
    }
}
